package org.javarosa.cdctz.shell;

import java.io.IOException;
import java.util.Hashtable;
import java.util.Vector;

import javax.microedition.midlet.MIDlet;

import org.javarosa.activity.splashscreen.SplashScreenActivity;
import org.javarosa.cdctz.properties.CdcTzAppProperties;
import org.javarosa.cdctz.util.CdcTzContext;
import org.javarosa.cdctz.util.TempPatientList;
import org.javarosa.cdctz.util.TempPatientRegActivity;
import org.javarosa.cdctz.util.TempPatientSelectActivity;
import org.javarosa.communication.http.HttpTransportModule;
import org.javarosa.communication.http.HttpTransportProperties;
import org.javarosa.communication.ui.CommunicationUIModule;
import org.javarosa.core.Context;
import org.javarosa.core.JavaRosaServiceProvider;
import org.javarosa.core.api.Constants;
import org.javarosa.core.api.IActivity;
import org.javarosa.core.api.IModule;
import org.javarosa.core.api.IShell;
import org.javarosa.core.api.IView;
import org.javarosa.core.model.CoreModelModule;
import org.javarosa.core.model.FormDef;
import org.javarosa.core.model.instance.DataModelTree;
import org.javarosa.core.model.storage.FormDefRMSUtility;
import org.javarosa.core.model.utils.DateUtils;
import org.javarosa.core.services.properties.JavaRosaPropertyRules;
import org.javarosa.core.services.transport.TransportMethod;
import org.javarosa.core.util.PropertyUtils;
import org.javarosa.core.util.WorkflowStack;
import org.javarosa.core.util.externalizable.DeserializationException;
import org.javarosa.formmanager.FormManagerModule;
import org.javarosa.formmanager.activity.FormEntryActivity;
import org.javarosa.formmanager.activity.FormEntryContext;
import org.javarosa.formmanager.activity.FormListActivity;
import org.javarosa.formmanager.activity.FormTransportActivity;
import org.javarosa.formmanager.activity.ModelListActivity;
import org.javarosa.formmanager.utility.RMSRetreivalMethod;
import org.javarosa.formmanager.utility.ReferenceRetrievalMethod;
import org.javarosa.formmanager.utility.TransportContext;
import org.javarosa.formmanager.view.Commands;
import org.javarosa.formmanager.view.chatterbox.util.ChatterboxContext;
import org.javarosa.formmanager.view.chatterbox.widget.ExtendedWidgetsModule;
import org.javarosa.formmanager.view.chatterbox.widget.GraphWidget;
import org.javarosa.formmanager.view.chatterbox.widget.ImmunizationWidget;
import org.javarosa.formmanager.view.chatterbox.widget.chart.WHOWeightTemplate;
import org.javarosa.j2me.storage.rms.RMSStorageModule;
import org.javarosa.model.xform.XFormSerializingVisitor;
import org.javarosa.model.xform.XFormsModule;
import org.javarosa.patient.PatientModule;
import org.javarosa.patient.entry.activity.PatientEntryActivity;
import org.javarosa.patient.model.Patient;
import org.javarosa.patient.model.data.NumericListData;
import org.javarosa.patient.storage.PatientRMSUtility;
import org.javarosa.patient.util.DateValueTuple;
import org.javarosa.patient.util.ImmunizationAnswerDataSerializer;
import org.javarosa.patient.util.PatientPreloadHandler;
import org.javarosa.referral.ReferralModule;
import org.javarosa.referral.activity.ReferralReport;
import org.javarosa.referral.util.ReportContext;
import org.javarosa.reminders.RemindersModule;
import org.javarosa.reminders.activity.DisplayReminderActivity;
import org.javarosa.reminders.util.INotificationReceiver;
import org.javarosa.reminders.util.ReminderListContext;
import org.javarosa.reminders.util.ReminderNotifierDaemon;
import org.javarosa.reminders.util.ReminderPreloadHandler;
import org.javarosa.services.properties.activity.PropertyScreenActivity;
import org.javarosa.user.activity.LoginActivity;
import org.javarosa.user.model.User;
import org.javarosa.xform.util.XFormAnswerDataSerializer;
import org.javarosa.xform.util.XFormUtils;

/**
 * This is the shell for the CDC Tanzania application.
 * 
 * It is responsible for managing the workflow of the
 * application.
 * 
 * @author Clayton Sims
 *
 */
public class CdcTzShell implements IShell, INotificationReceiver {
	// List of views that are used by this shell
	MIDlet midlet;

	WorkflowStack stack;
	CdcTzContext context;
	
	IActivity currentActivity;
	IActivity mostRecentListActivity; //should never be accessed, only checked for type
	
	Vector pendingReminders;
	
	private ReminderNotifierDaemon notifier;
	
	
	public CdcTzShell() {
		stack = new WorkflowStack(); 
		context = new CdcTzContext();
		
		pendingReminders = new Vector();
	}

	public void exitShell() {
		midlet.notifyDestroyed();
	}

	public void run() {
		init();
		workflow(null, null, null);
	}

	private void init() {
		loadModules();
		loadProperties();
		registerCustomPrototypes();
		
		FormDefRMSUtility formDef = (FormDefRMSUtility)JavaRosaServiceProvider.instance().getStorageManager().getRMSStorageProvider().getUtility(FormDefRMSUtility.getUtilityName());
		PatientRMSUtility patientRms = (PatientRMSUtility)JavaRosaServiceProvider.instance().getStorageManager().getRMSStorageProvider().getUtility(PatientRMSUtility.getUtilityName());
		
		if (patientRms.getNumberOfRecords() == 0) {
			addTempPatients(patientRms);
		}
		
		// For now let's add the dummy form.
		if (formDef.getNumberOfRecords() == 0) {
			formDef.writeToRMS(XFormUtils.getFormFromResource("/shortform.xhtml"));
			formDef.writeToRMS(XFormUtils.getFormFromResource("/ehealth-demo.xhtml"));
			formDef.writeToRMS(XFormUtils.getFormFromResource("/tz-e-ctc.xhtml"));
			formDef.writeToRMS(XFormUtils.getFormFromResource("/pathfinder.xhtml"));
		}
		
		notifier = (ReminderNotifierDaemon)JavaRosaServiceProvider.instance().getDaemon(ReminderNotifierDaemon.DEFAULT_NAME);
		notifier.setNotificationReceiver(this);
	}
	
	private void loadModules() {
		new RMSStorageModule().registerModule(context);
		new XFormsModule().registerModule(context);
		new CoreModelModule().registerModule(context);
		new FormManagerModule().registerModule(context);
		new HttpTransportModule().registerModule(context);
		new ReferralModule().registerModule(context);
		new RemindersModule().registerModule(context);
		new ExtendedWidgetsModule().registerModule(context);
		new PatientModule().registerModule(context);
		new CommunicationUIModule().registerModule(context);
	}
	
	private void registerCustomPrototypes () {
		String[] classes = {
				"org.javarosa.model.GraphDataGroup",
				"org.javarosa.patient.model.data.ImmunizationAnswerData"
		};
		
		JavaRosaServiceProvider.instance().registerPrototypes(classes);
	}
	
	private void addTempPatients (PatientRMSUtility rms) {
		Patient tempPatient1 = new Patient();
		Patient tempPatient2 = new Patient();
		Patient tempPatient3 = new Patient();
		Patient tempPatient4 = new Patient();
		
		tempPatient1.setBirthDate(DateUtils.getDateFromString("1985-01-25"));
		tempPatient1.setFamilyName("Sims");
		tempPatient1.setGivenName("Clayton");
		tempPatient1.setGender(Patient.SEX_MALE);
		
		NumericListData weightRecord1 = new NumericListData();
		weightRecord1.addMeasurement(new DateValueTuple(DateUtils.getDateFromString("2008-02-25"),45));
		weightRecord1.addMeasurement(new DateValueTuple(DateUtils.getDateFromString("2008-03-25"),43));
		weightRecord1.addMeasurement(new DateValueTuple(DateUtils.getDateFromString("2008-04-25"),49));
		weightRecord1.addMeasurement(new DateValueTuple(DateUtils.getDateFromString("2008-05-25"),51));
		weightRecord1.addMeasurement(new DateValueTuple(DateUtils.getDateFromString("2008-06-25"),54));
		weightRecord1.addMeasurement(new DateValueTuple(DateUtils.getDateFromString("2008-07-25"),55));
		tempPatient1.setRecord("weight", weightRecord1);
		tempPatient1.setTreatmentStartDate(DateUtils.getDateFromString("2007-06-20"));
		tempPatient1.setTreatmentRegimen("1c:ZDV-3TC-EFV");
		
		tempPatient2.setBirthDate(DateUtils.getDateFromString("1969-07-20"));
		tempPatient2.setFamilyName("Lesh");
		tempPatient2.setGivenName("Neal");
		tempPatient2.setGender(Patient.SEX_MALE);
		
		NumericListData weightRecord2 = new NumericListData();
		weightRecord2.addMeasurement(new DateValueTuple(DateUtils.getDateFromString("2008-01-25"),34));
		weightRecord2.addMeasurement(new DateValueTuple(DateUtils.getDateFromString("2008-03-25"),38));
		weightRecord2.addMeasurement(new DateValueTuple(DateUtils.getDateFromString("2008-04-16"),47));
		weightRecord2.addMeasurement(new DateValueTuple(DateUtils.getDateFromString("2008-05-25"),38));
		weightRecord2.addMeasurement(new DateValueTuple(DateUtils.getDateFromString("2008-06-25"),47));
		weightRecord2.addMeasurement(new DateValueTuple(DateUtils.getDateFromString("2008-07-25"),38));
		tempPatient2.setRecord("weight", weightRecord2);
		
		tempPatient3.setBirthDate(DateUtils.getDateFromString("1977-04-06"));
		tempPatient3.setFamilyName("DeRenzi");
		tempPatient3.setGivenName("Brianna");
		tempPatient3.setGender(Patient.SEX_FEMALE);
		
		NumericListData weightRecord3 = new NumericListData();
		weightRecord3.addMeasurement(new DateValueTuple(DateUtils.getDateFromString("2007-08-25"),36));
		weightRecord3.addMeasurement(new DateValueTuple(DateUtils.getDateFromString("2007-09-25"),40));
		weightRecord3.addMeasurement(new DateValueTuple(DateUtils.getDateFromString("2007-10-25"),43));
		weightRecord3.addMeasurement(new DateValueTuple(DateUtils.getDateFromString("2007-11-25"),45));
		weightRecord3.addMeasurement(new DateValueTuple(DateUtils.getDateFromString("2007-12-25"),47));
		weightRecord3.addMeasurement(new DateValueTuple(DateUtils.getDateFromString("2008-01-25"),48));		
		weightRecord3.addMeasurement(new DateValueTuple(DateUtils.getDateFromString("2008-02-25"),48));
		weightRecord3.addMeasurement(new DateValueTuple(DateUtils.getDateFromString("2008-03-25"),43));
		weightRecord3.addMeasurement(new DateValueTuple(DateUtils.getDateFromString("2008-04-25"),42));
		weightRecord3.addMeasurement(new DateValueTuple(DateUtils.getDateFromString("2008-05-25"),38));
		weightRecord3.addMeasurement(new DateValueTuple(DateUtils.getDateFromString("2008-06-25"),39));
		weightRecord3.addMeasurement(new DateValueTuple(DateUtils.getDateFromString("2008-07-25"),42));
		tempPatient3.setRecord("weight", weightRecord3);
		
		tempPatient4.setBirthDate(DateUtils.getDateFromString("2008-06-01"));
		tempPatient4.setFamilyName("Roos");
		tempPatient4.setGivenName("Drew");
		tempPatient4.setGender(Patient.SEX_MALE);
		
		NumericListData weightRecord4 = new NumericListData();
		weightRecord4.addMeasurement(new DateValueTuple(DateUtils.getDateFromString("2008-06-01"),15));
		weightRecord4.addMeasurement(new DateValueTuple(DateUtils.getDateFromString("2008-07-01"),18));
		weightRecord4.addMeasurement(new DateValueTuple(DateUtils.getDateFromString("2008-07-26"),20));
		tempPatient4.setRecord("weight", weightRecord4);	
		
		rms.writeToRMS(tempPatient1);		
		rms.writeToRMS(tempPatient2);		
		rms.writeToRMS(tempPatient3);
		rms.writeToRMS(tempPatient4);
	}
	
	private void workflow(IActivity lastActivity, String returnCode, Hashtable returnVals) {
		if (returnVals == null)
			returnVals = new Hashtable(); //for easier processing
		
		if (lastActivity != currentActivity) {
			System.out.println("Received 'return' event from activity other than the current activity" +
					" (such as a background process). Can't handle this yet");
			return;
		}
		
		if (returnCode == Constants.ACTIVITY_SUSPEND || returnCode == Constants.ACTIVITY_NEEDS_RESOLUTION) {
			stack.push(lastActivity);
			workflowLaunch(lastActivity, returnCode, returnVals);
		} else {
			if (stack.size() > 0) {
				workflowResume(stack.pop(), lastActivity, returnCode, returnVals);
			} else {
				workflowLaunch(lastActivity, returnCode, returnVals);
				if (lastActivity != null)
					lastActivity.destroy();
			}
		}
	}
	
	private void workflowLaunch (IActivity returningActivity, String returnCode, Hashtable returnVals) {
		if (returningActivity == null) {
			
			launchActivity(new SplashScreenActivity(this, "/splash.gif"), context);
			
		} else if (returningActivity instanceof SplashScreenActivity) {
			
			//#if javarosa.dev.shortcuts
			launchActivity(new TempPatientSelectActivity(this, "Select Patient"), context);
			//#else 
			launchActivity(new LoginActivity(this, "Login"), context);
			//#endif
			
		} else if (returningActivity instanceof LoginActivity) {
			
			Object returnVal = returnVals.get(LoginActivity.COMMAND_KEY);
			if (returnVal == "USER_VALIDATED") {
				User user = (User)returnVals.get(LoginActivity.USER);
				if (user != null)
					context.setCurrentUser(user.getUsername());
				
				launchActivity(new TempPatientSelectActivity(this, "Select Patient"), context);
			} else if (returnVal == "USER_CANCELLED") {
				exitShell();
			}
			
		} else if (returningActivity instanceof TempPatientSelectActivity) {

			String returnVal = (String)returnVals.get(FormListActivity.COMMAND_KEY);
			if (returnVal == Commands.CMD_SETTINGS) {
				launchActivity(new PropertyScreenActivity(this), context);
			} else if (returnVal == TempPatientList.SELECT_PATIENT) {
				context.setPatientId(((Integer)returnVals.get(TempPatientSelectActivity.PATIENT_ID_KEY)).intValue());
				launchActivity(getNewFormListActivity(), context);
				
			} else if (returnVal == TempPatientList.CMD_NEW_STRING) {
				context.setElement("ENTRY_MODE", "SINGLE");
				launchActivity(new PatientEntryActivity(this), context);
			} else if (returnVal == TempPatientList.CMD_BATCH_NEW_STRING) {
				context.setElement("ENTRY_MODE", "BATCH");
				launchActivity(new PatientEntryActivity(this), context);
			} else if (returnVal == TempPatientList.CMD_UPDATE_STRING) {
				Context updateContext = this.context.clone();
				updateContext.setElement("PATIENT_ID_KEY", returnVals.get(TempPatientSelectActivity.PATIENT_ID_KEY));
				launchActivity(new TempPatientRegActivity(this), updateContext);
			} else if (returnVal == Commands.CMD_EXIT) {
				exitShell();
			}
			
		} else if (returningActivity instanceof FormListActivity) {
		
			String returnVal = (String)returnVals.get(FormListActivity.COMMAND_KEY);
			if (returnVal == Commands.CMD_SETTINGS) { //keep this?
				launchActivity(new PropertyScreenActivity(this), context);
			} else if (returnVal == Commands.CMD_VIEW_DATA) {
				launchActivity(new ModelListActivity(this), context);
			} else if (returnVal == Commands.CMD_SELECT_XFORM) {
				launchFormEntryActivity(context, ((Integer)returnVals.get(FormListActivity.FORM_ID_KEY)).intValue(), -1);
			} else if (returnVal == DisplayReminderActivity.VIEW_REMINDERS.getLabel()) {
				launchDisplayReminderActivity(context, ReminderListContext.VIEW_ALL);
			} else if (returnVal == Commands.CMD_EXIT) {
				launchActivity(new TempPatientSelectActivity(this, "Select Patient"), context);
			}
			
		} else if (returningActivity instanceof ModelListActivity) {
			
			Object returnVal = returnVals.get(ModelListActivity.returnKey);
			if (returnVal == ModelListActivity.CMD_MSGS) {
				launchFormTransportActivity(context, TransportContext.MESSAGE_VIEW, null);
			} else if (returnVal == ModelListActivity.CMD_EDIT) {
				launchFormEntryActivity(context, ((FormDef)returnVals.get("form")).getID(),
						((DataModelTree)returnVals.get("data")).getId());
			} else if (returnVal == ModelListActivity.CMD_SEND) {
				launchFormTransportActivity(context, TransportContext.SEND_DATA, (DataModelTree)returnVals.get("data"));
			} else if (returnVal == ModelListActivity.CMD_BACK) {
				launchActivity(getNewFormListActivity(), context);
			}
			
		} else if (returningActivity instanceof FormEntryActivity) {
			if (context.getPatientId() != -1) {
				PatientRMSUtility utility = (PatientRMSUtility)JavaRosaServiceProvider.instance().getStorageManager().getRMSStorageProvider().getUtility(PatientRMSUtility.getUtilityName());
				utility.updateToRMS(context.getPatientId(), (Patient)context.getElement("PATIENT"));
				context.removeElement("PATIENT");
			}
			
			if (((Boolean)returnVals.get("FORM_COMPLETE")).booleanValue()) {
				//launchFormTransportActivity(context, TransportContext.SEND_DATA, (DataModelTree)returnVals.get("DATA_MODEL"));
				FormEntryContext fecontext = (FormEntryContext) returningActivity
						.getActivityContext();
				launchReportActivity(context, ((DataModelTree) returnVals
						.get("DATA_MODEL")).getId(), fecontext.getFormName());
			} else {
				relaunchListActivity();
			}

		} else if (returningActivity instanceof FormTransportActivity) {
			if (returnVals.get(FormTransportActivity.RETURN_KEY) == FormTransportActivity.NEW_DESTINATION) {
				TransportMethod transport = JavaRosaServiceProvider.instance()
						.getTransportManager().getTransportMethod(
								JavaRosaServiceProvider.instance()
										.getTransportManager()
										.getCurrentTransportMethod());
				IActivity activity = transport
						.getDestinationRetrievalActivity();
				activity.setShell(this);
				this.launchActivity(activity, context);
			} else {
				relaunchListActivity();
			}
		} else if (returningActivity instanceof ReferralReport) {
			relaunchListActivity();
		} else if (returningActivity instanceof DisplayReminderActivity) {
			this.pendingReminders.removeAllElements();
			notifier.start();
			relaunchListActivity();
		} else if (returningActivity instanceof PatientEntryActivity) {
			FormDef def = (FormDef)returnVals.get(PatientEntryActivity.PATIENT_ENTRY_FORM_KEY);
			if(def != null) {
				ReferenceRetrievalMethod method = new ReferenceRetrievalMethod();
				method.setFormDef(def);
				launchFormEntryActivity(context, -1, -1, method);
			} else {
				//We're done, patient's in.
				if("SINGLE".equals(returningActivity.getActivityContext().getElement("ENTRY_MODE"))) {
					//Go straight to form entry if they just had one patient
					launchActivity(getNewFormListActivity(), context);					
				}
			}
		}
	}
	
	private void workflowResume (IActivity suspendedActivity, IActivity completingActivity,
								 String returnCode, Hashtable returnVals) {
		
		//default action
		Context newContext = new Context(context);
		newContext.addAllValues(returnVals);
		resumeActivity(suspendedActivity, newContext);
	}
		
	private void launchActivity (IActivity activity, Context context) {
		if (activity instanceof FormListActivity || activity instanceof ModelListActivity) {
			mostRecentListActivity = activity;
			if(pendingReminders.size() > 0) {
				launchDisplayReminderActivity(this.context, ReminderListContext.VIEW_TRIGGERED);
				return;
			}
		}
		
		currentActivity = activity;
		activity.start(context);
	}
	
	private void resumeActivity (IActivity activity, Context context) {
		currentActivity = activity;
		activity.resume(context);
	}	
	
	private void launchFormEntryActivity (CdcTzContext context, int formID, int instanceID) {
		launchFormEntryActivity(context, formID, instanceID, null);
	}
	
	private void launchFormEntryActivity (CdcTzContext context, int formID, int instanceID, ReferenceRetrievalMethod method) {
		FormEntryActivity entryActivity = new FormEntryActivity(this, new FormEntryViewFactory());
		PatientRMSUtility utility = (PatientRMSUtility)JavaRosaServiceProvider.instance().getStorageManager().getRMSStorageProvider().getUtility(PatientRMSUtility.getUtilityName());
		Patient tempPatient = new Patient();
		try {
			if(context.getPatientId() != -1) {
				utility.retrieveFromRMS(context.getPatientId(), tempPatient);
			} else {
				tempPatient = null;
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (DeserializationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		context.setElement("PATIENT", tempPatient);
		
		ChatterboxContext formEntryContext = new ChatterboxContext(context);
		GraphWidget graph = new GraphWidget();
		WHOWeightTemplate template = new WHOWeightTemplate();
		template.setPatient(tempPatient);
		graph.registerTemplate(template);
		formEntryContext.addCustomWidget(graph);
		formEntryContext.addCustomWidget(new ImmunizationWidget());
		formEntryContext.setFormID(formID);

		formEntryContext.addPreloadHandler(new PatientPreloadHandler(tempPatient));
		formEntryContext.addPreloadHandler(new ReminderPreloadHandler(tempPatient));
		
		if (instanceID != -1)
			formEntryContext.setInstanceID(instanceID);
		
		if(method != null) {
			entryActivity.setRetrievalMethod(method);
		} else {
			entryActivity.setRetrievalMethod(new RMSRetreivalMethod());
		}
		
		launchActivity(entryActivity, formEntryContext);
	}
	
	private void launchFormTransportActivity (Context context, String task, DataModelTree data) {
		FormTransportActivity formTransport = new FormTransportActivity(this);
		XFormSerializingVisitor visitor = new XFormSerializingVisitor();
		XFormAnswerDataSerializer serializer = new XFormAnswerDataSerializer();
		serializer.registerAnswerSerializer(new ImmunizationAnswerDataSerializer());
		visitor.setAnswerDataSerializer(serializer);
		formTransport.setDataModelSerializer(visitor);
		formTransport.setData(data); //why isn't this going in the context?
		TransportContext msgContext = new TransportContext(context);		
		msgContext.setRequestedTask(task);

		launchActivity(formTransport, msgContext);
	}
	
	private void launchReportActivity(Context context, int modelId, String formName) {
		ReferralReport report = new ReferralReport(this);
		ReportContext activityContext = new ReportContext();
		activityContext.setModelId(modelId);
		activityContext.setFormName(formName);
		
		launchActivity(report, activityContext);
	}
	
	private void relaunchListActivity () {
		if(pendingReminders.size() > 0) {
			launchDisplayReminderActivity(this.context, ReminderListContext.VIEW_TRIGGERED);
		}
		if (mostRecentListActivity instanceof FormListActivity) {
			launchActivity(getNewFormListActivity(), context);
		} else if (mostRecentListActivity instanceof ModelListActivity) {
			launchActivity(new ModelListActivity(this), context);
		} else {
			throw new IllegalStateException("Trying to resume list activity when no most recent set");
		}
	}
	
	private FormListActivity getNewFormListActivity() {
		FormListActivity returnVal = new FormListActivity(this, "Forms List");
		returnVal.addNewMenuCommand(DisplayReminderActivity.VIEW_REMINDERS);
		return returnVal;
	}
	
	/* (non-Javadoc)
	 * @see org.javarosa.shell.IShell#activityCompeleted(org.javarosa.activity.IActivity)
	 */
	public void returnFromActivity(IActivity activity, String returnCode, Hashtable returnVals) {
		//activity.halt(); //i don't think this belongs here? the contract reserves halt for unexpected halts;
						   //an activity calling returnFromActivity isn't halting unexpectedly
		workflow(activity, returnCode, returnVals);
	}

	public boolean setDisplay(IActivity callingActivity, IView display) {
		if(callingActivity == currentActivity) {
			JavaRosaServiceProvider.instance().getDisplay().setView(display);
			return true;
		}
		else {
			//#if debug.output==verbose
			System.out.println("Activity: " + callingActivity + " attempted, but failed, to set the display");
			//#endif
			return false;
		}
	}

	public void setMIDlet(MIDlet midlet) {
		this.midlet = midlet;
	}

	/* (non-Javadoc)
	 * @see org.javarosa.reminders.util.INotificationReceiver#receiveReminders(java.util.Vector)
	 */
	public void receiveReminders(Vector reminders) {
		this.pendingReminders = reminders;
		if(currentActivity instanceof FormListActivity) {
			//If we're already on the formlist, interrupt it, and start this up
			launchDisplayReminderActivity(this.context, ReminderListContext.VIEW_TRIGGERED);
		}
	}
	
	public void launchDisplayReminderActivity(Context context, int viewMode) {
		DisplayReminderActivity activity = new DisplayReminderActivity(this);
		
		notifier.stop();
		if(viewMode == ReminderListContext.VIEW_TRIGGERED) {
			activity.setReminders(this.pendingReminders);
		} else {
			activity.setReminders(notifier.getReminders());
		}
		ReminderListContext activityContext = new ReminderListContext(context);
		activityContext.setViewMode(viewMode);
		
		this.launchActivity(activity, activityContext);
	}

	private String initProperty(String propName, String defaultValue) {
		Vector propVal = JavaRosaServiceProvider.instance().getPropertyManager().getProperty(propName);
		if (propVal == null || propVal.size() == 0) {
			propVal = new Vector();
			propVal.addElement(defaultValue);
			JavaRosaServiceProvider.instance().getPropertyManager().setProperty(propName, propVal);
			//#if debug.output==verbose
			System.out.println("No default value for [" + propName
					+ "]; setting to [" + defaultValue + "]"); // debug
			//#endif
			return defaultValue;
		}
		return (String) propVal.elementAt(0);
	}

	private void loadProperties() {
		JavaRosaServiceProvider.instance().getPropertyManager().addRules(new JavaRosaPropertyRules());
		JavaRosaServiceProvider.instance().getPropertyManager().addRules(new CdcTzAppProperties());

		initProperty("DeviceID", PropertyUtils.genGUID(25));		
		initProperty(HttpTransportProperties.POST_URL_LIST_PROPERTY, "http://update.cell-life.org/save_dump_org.php");
		initProperty(HttpTransportProperties.POST_URL_PROPERTY, "http://update.cell-life.org/save_dump_org.php");				
//		initProperty(HttpTransportProperties.POST_URL_LIST_PROPERTY, "http://openrosa.org/testsubmit.html");
//		initProperty(HttpTransportProperties.POST_URL_PROPERTY, "http://openrosa.org/testsubmit.html");
	}
}
